package com.hengfoxwolf.jetpackdemo.defineview
import android.content.Context
import android.os.SystemClock
import android.util.AttributeSet
import android.widget.Chronometer
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

class LifeCycleChronometer @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : Chronometer(context,attributeSet), DefaultLifecycleObserver {

    private var elapsedTime = 0L

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        //获取现在时间减暂停使用时间回到上次使用时间
        base = SystemClock.elapsedRealtime() - elapsedTime
        start()
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        //保存上次时间
        elapsedTime = SystemClock.elapsedRealtime() - base
        stop()
    }

}